import { useCallback } from 'react';
import { useEffectRef } from '.';

function useSetter(object, keys) {
  const objectRef = useEffectRef(object);
  const keysRef = useEffectRef(keys);

  return useCallback((value) => {
    let { current: target } = objectRef;
    let keyList = keysRef.current;
    if (typeof keyList === 'string') keyList = [keyList];
    keyList = keyList?.slice() ?? [];

    if (!keyList.length) return false;

    const last = keyList.pop();
    for (const key of keyList) {
      target = object?.[key] ?? null;
      if (target == null) break;
    }

    if (target == null || typeof target !== 'object') return false;
    target[last] = value;
    return true;
  }, []);
}

export default useSetter;
